import threading
import requests
import os

# 定义下载函数
def download_file(url, save_path):
    try:
        # 发起请求，支持重定向
        response = requests.get(url, stream=True, allow_redirects=True)
        response.raise_for_status()  # 检查请求是否成功

        # 获取文件名
        filename = url.split("/")[-1]
        if "Content-Disposition" in response.headers:
            # 如果有Content-Disposition头，从中提取文件名
            content_disposition = response.headers["Content-Disposition"]
            filename = content_disposition.split("filename=")[-1].strip('"')

        # 拼接保存路径
        save_file_path = os.path.join(save_path, filename)

        # 下载文件
        with open(save_file_path, "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)

        print(f"文件已下载到 {save_file_path}")
    except Exception as e:
        print(f"下载 {url} 时出错: {e}")

# 定义多线程下载函数
def multi_download(urls, save_path, max_threads=12):
    threads = []
    for url in urls:
        thread = threading.Thread(target=download_file, args=(url, save_path))
        threads.append(thread)
        thread.start()

        # 等待线程池中的线程数量小于最大线程数
        if len(threads) >= max_threads:
            for thread in threads:
                thread.join()
            threads = []

    # 等待剩余线程完成
    for thread in threads:
        thread.join()

# 示例使用
if __name__ == "__main__":
    # 下载的URL列表
    urls = [
        "https://tlcdn-sync.mcsl.com.cn/core/Spigot/1.21/Latest/download"
    ]

    # 保存路径
    save_path = "./"  # 下载文件保存的目录
    # 开始多线程下载
    multi_download(urls, save_path)